package modules

import "test_api/dao"

type UserModel struct {
	Id       int    `gorm:"primary_key" json:"id"`
	Username string `json:"username"`
	Nickname string `json:"nickname"`
}

// CreateUserRequest 用户创建请求结构体
type CreateUserRequest struct {
	Username string `json:"username"`
	Nickname string `json:"nickname"`
}

type UpdateUserRequest struct {
	Username string `json:"username"`
	Nickname string `json:"nickname"`
}

func (UserModel) TableName() string {
	return "dtm_user"
}

func (u UserModel) GetUserInfo(id int) (UserModel, error) {
	var user UserModel
	err := dao.Db.Where("id = ?", id).First(&user).Error
	return user, err
}

// AddUser 添加用户
func (u UserModel) AddUser(data CreateUserRequest) (int, error) {
	user := UserModel{
		Username: data.Username,
		Nickname: data.Nickname,
	}

	dao.Db.Create(&user)

	return user.Id, dao.Db.Error
}

// UpdateUser 修改用户
func (u UserModel) UpdateUser(id int, data UpdateUserRequest) (int, error) {
	var user UserModel
	result := dao.Db.First(&user, id)
	if result.Error != nil {
		return 0, result.Error
	}
	user.Username = data.Username
	user.Nickname = data.Nickname
	result = dao.Db.Save(&user)
	return user.Id, dao.Db.Error
}
